package com.yuncheng.oaApi.FlowController;


import com.yuncheng.entity.YcSysUser;
import com.yuncheng.oaApi.constant.OaCommonFlowConstant;
import com.yuncheng.oaApi.constant.OaLogConstant;
import com.yuncheng.oaApi.constant.OaFlowConstant;
import com.yuncheng.oaApi.vo.OaFlowVo;
import com.yuncheng.oaApi.vo.OaJbzbVo;
import com.yuncheng.oaApi.vo.OaReturnVo;
import com.yuncheng.oaApi.vo.Result;
import com.yuncheng.spcyApi.service.ISpcyLogService;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.oaApi.FlowService.NewOajbzbOaFlowService;
import com.yuncheng.annotation.AutoLog;
import com.yuncheng.oaApi.busService.OaFlowNodeDbrService;
import com.yuncheng.oaApi.busService.MyLcFlowService;
import com.yuncheng.oaApi.entity.*;
import com.yuncheng.oaApi.mapper.OaJbzbFlowMapper;
import com.yuncheng.oaApi.service.*;
import com.yuncheng.spcyApi.utils.DateConvert;
import com.yuncheng.oaApi.utils.GetUuIdUtils;
import com.yuncheng.utils.ThreadContextHelper;
import com.yuncheng.vo.*;
import groovy.lang.Lazy;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import java.lang.reflect.InvocationTargetException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

@Api(tags = "NEW_OA-加班值班管理")
@RestController
@RequestMapping("/api/spzx-oa/newflow-jbzb")
public class NewOaJbzbFlowController {
    private static final Logger log = LoggerFactory.getLogger(NewOaJbzbFlowController.class);

    @Resource
    private OaJbzbFlowMapper oaJbzbFlowMapper;

    @Resource
    private NewOajbzbOaFlowService newOajbzbFlowService;

    @Resource
    private IOaJbzbglService oaJbzbglService;

    @Resource
    private IOaSpcySqsxJobService spcySqsxJobService;

    @Resource
    private ISpcyLogService spcyLogService;

    @Resource
    private IOaYcSysUserService ycSysUserService;

    @Resource
    @Lazy
    private IOaSysTzMessageService sysTzMessageService;

    @Resource
    @Lazy
    private MyLcFlowService myLcFlowService;

    @Resource
    @Lazy
    private OaFlowNodeDbrService oaFlowNodeDbrService;

    @Resource
    @Lazy
    private IOaSysFlowTempleService sysFlowTempleService;

    @Resource
    @Lazy
    private IOaSysFlowNodeService sysFlowNodeService;

    @Resource
    @Lazy
    private IOaProcessBusinessService oaProcessBusinessService;


    /**
     * 流程列表分页查询
     *
     * @param oaJbzbVo
     * @param pageNo
     * @param pageSize
     * @param onlyCurrentUser
     * @return
     */
    @AutoLog(value = "流程监控-分页查询")
    @ApiOperation(value = "流程监控-分页查询")
    @GetMapping("flowJkPage")
    public HttpResult<?> flowJkPage(
            OaJbzbVo oaJbzbVo,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "onlyCurrentUser", defaultValue = "false") boolean onlyCurrentUser) {
        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null) {
            return HttpResult.error("请重新登录，Token已失效！");
        }
        Page<OaJbzbVo> page = new Page<>(pageNo, pageSize);
        oaJbzbVo.setFlcmc(OaFlowConstant.OA_JBZB_NAME);

        IPage<OaJbzbVo> list = null;
        if (StringUtils.isNotBlank(oaJbzbVo.getOaid())){
            OaJbzbgl xcxxspgl = oaJbzbglService.getById(oaJbzbVo.getOaid());
            if (xcxxspgl != null){
                list = oaJbzbFlowMapper.flowJkPage(page, onlyCurrentUser, user, oaJbzbVo);
            }
        }

        return HttpResult.ok(list);
    }

    /**
     * 流程列表分页查询
     *
     * @param oaJbzbVo
     * @param pageNo
     * @param pageSize
     * @param onlyCurrentUser
     * @return
     */
    @AutoLog(value = "流程列表-分页查询")
    @ApiOperation(value = "流程列表-分页查询")
    @GetMapping("flowJobPage")
    public HttpResult<?> flowJobPage(
            OaJbzbVo oaJbzbVo,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(name = "onlyCurrentUser", defaultValue = "true") boolean onlyCurrentUser) {
        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null) {
            return HttpResult.error("请重新登录，Token已失效！");
        }
        if (StringUtils.isBlank(oaJbzbVo.getFblzt())) {
            oaJbzbVo.setFblzt(OaCommonFlowConstant.BLZT_DB);
        }
        Page<OaJbzbVo> page = new Page<>(pageNo, pageSize);
        oaJbzbVo.setFlcmc(OaFlowConstant.OA_JBZB_NAME);
        IPage<OaJbzbVo> list = oaJbzbFlowMapper.flowJobPage(page, onlyCurrentUser, user, oaJbzbVo);
        return HttpResult.ok(list);
    }


    /**
     * 我的已办
     */
    @AutoLog(value = "流程列表-我的已办")
    @ApiOperation(value = "流程列表-我的已办")
    @GetMapping("myJobPage")
    public HttpResult<?> myJobPage(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            OaJbzbVo oaJbzbVo) {

        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null) {
            return HttpResult.error("请重新登录，Token已失效！");
        }
        Page<OaJbzbVo> page = new Page<>(pageNo, pageSize);
        IPage<OaJbzbVo> list = oaJbzbFlowMapper.myYbFlowPage(page, true, user, oaJbzbVo);
        return HttpResult.ok(list);
    }

    /**
     * 数据修订
     */
    @AutoLog(value = "列表-数据修订")
    @ApiOperation(value = "列表-数据修订")
    @GetMapping("Pagesjxd")
    public HttpResult<?> Pagesjxd(
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
            OaJbzbVo oaJbzbVo) {

        CurrentUserVo user = ThreadContextHelper.getCurrentUser();
        if (user == null) {
            return HttpResult.error("请重新登录，Token已失效！");
        }

        Page<OaJbzbVo> page = new Page<>(pageNo, pageSize);
        IPage<OaJbzbVo> list = oaJbzbFlowMapper.myYbFlowPage(page, false, user, oaJbzbVo);
        return HttpResult.ok(list);
    }


    @AutoLog(value = "发起加班值班管理")
    @ApiOperation(value = "发起加班值班管理")
    @PostMapping(value = "initBzFlow")
    public HttpResult<?> initBzFlow(@RequestBody OaJbzbgl oaJbzbgl) {
        String oaid = "";
        //当前人的id
        CurrentUserVo currentUser = ThreadContextHelper.getCurrentUser();
        if (currentUser == null) {
            return HttpResult.error("当前登录已失效，请重新登录");
        }
        if (StringUtils.isNotBlank(oaJbzbgl.getId())) {
            OaJbzbgl oaids = oaJbzbglService.getById(oaJbzbgl.getId());
            ConvertUtils.register(new DateConvert(), Date.class);
            try {
                BeanUtils.populate(oaids, BeanUtils.describe(oaJbzbgl));
            } catch (IllegalAccessException e) {
                log.error("出错-保存事项【非法访问异常】,{}", e.getMessage());
            } catch (InvocationTargetException e) {
                log.error("出错-保存事项【调用TargetException】,{}", e.getMessage());
            } catch (NoSuchMethodException e) {
                log.error("出错-找不到可用方法", e.getMessage());
            }
            oaid = oaJbzbgl.getId();

            // Date日期单独做处理


            oaJbzbglService.updateById(oaids);
        } else {
            oaid = GetUuIdUtils.ReplaceUuId();
            String timeStr = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));

            oaJbzbgl.setId(oaid);
            oaJbzbgl.setFxm(currentUser.getName());
            oaJbzbgl.setFbm(currentUser.getDeptName());

            oaJbzbgl.setFuserid(currentUser.getId());
            oaJbzbgl.setFjbzbsqrq(timeStr);

            YcSysUser ycSysUserById = ycSysUserService.getYcSysUserById(currentUser.getId());
            oaJbzbgl.setFzw(ycSysUserById.getFzw());
            oaJbzbgl.setFlczt(OaCommonFlowConstant.FLOW_LCZB);

            oaJbzbglService.save(oaJbzbgl);
        }

        /**
         * @Author: lhb
         * @Description : 是否发起流程   如果是开始申请就跳转流程
         *               在这里设置 nextNodeName 指定下个环节节点 做当前跳转流程的判断，然后设置变量接收环节的值，写到nextNodeName中
         * @DateTime:
         * @Params: Fsffqlc
         */
        String msg = "保存成功";
        String lcmbCode = OaFlowConstant.OA_JBZB;
        OaJobEntity job = new OaJobEntity();
        // 初始化流程
        Result result = newOajbzbFlowService.createProcess(lcmbCode,oaid, currentUser);
        OaJbzbgl oaJbzbgl1 = oaJbzbglService.getById(oaid);
        List<OaProcessBusiness> oaProcessBusinessList = oaProcessBusinessService.list(new LambdaQueryWrapper<OaProcessBusiness>()
                .eq(OaProcessBusiness::getFpid, oaid));
        String bt =  currentUser.getName()+"提交的加班值班"; //标题
        String zy = "开始时间:["+oaJbzbgl1.getFjbzbksrq()+"  "+ oaJbzbgl1.getFjbzbkssj()+"]"+"\n"
                +"结束时间:["+ oaJbzbgl1.getFjbzbjsrq()+"  "+oaJbzbgl1.getFjbzbjssj() + "]"+"\n"
                + "时长:"+ oaJbzbgl1.getFjbzbsc()+"天";
        if (oaProcessBusinessList.size() == 0){
            //初始化的时候 像 流程业务主表添加拼接初始化数据
            oaProcessBusinessService.addProcess(oaid,zy,bt,lcmbCode,OaFlowConstant.OA);

        }else {
            String id = oaProcessBusinessList.get(0).getId();  //当前已经插入的主键id 然后更新 摘要信息
            OaProcessBusiness oaProcessBusiness = oaProcessBusinessService.getById(id);
            oaProcessBusiness.setFzy(zy);
            oaProcessBusinessService.updateById(oaProcessBusiness);

        }

        if (!result.isSuccess()) {
            return HttpResult.error(result.getMessage());
        } else {
             job = (OaJobEntity) result.getResult();
            if (job != null) {
                // 是否提交流程
                if (StringUtils.isBlank(oaid)) {
                    return HttpResult.error("参数丢失");
                }
                String nextnodeId = "";
                if (StringUtils.isNotBlank(oaJbzbgl.getFsffqlc()) && oaJbzbgl.getFsffqlc().equals(OaCommonFlowConstant.SFFQLC_YES)) {
                    if (StringUtils.isBlank(oaJbzbgl.getFbm())) {
                        return HttpResult.error("请完善个人信息部门名称栏");
                    }
                    if (StringUtils.isBlank(oaJbzbgl.getFzw())) {
                        return HttpResult.error("请完善个人信息职务栏");
                    }
                    if (StringUtils.isBlank(oaJbzbgl.getFlczt())) {
                        oaJbzbgl.setFlczt(OaCommonFlowConstant.FLOW_LCZB);
                    }

                    List<OaSysFlowTemple> templeList = sysFlowTempleService.list(new LambdaQueryWrapper<OaSysFlowTemple>().eq(OaSysFlowTemple::getFlcbm, lcmbCode));
                    String templeId = templeList.get(0).getId();

                    List<OaSysFlowNode> flowNodeList = sysFlowNodeService.list(new LambdaQueryWrapper<OaSysFlowNode>().eq(OaSysFlowNode::getFlcmbid, templeId)
                            .eq(OaSysFlowNode::getFjdmc, OaFlowConstant.JBZB_HJMC_FGSP));

                    List<OaSysFlowNode> flowNodeListdwld = sysFlowNodeService.list(new LambdaQueryWrapper<OaSysFlowNode>().eq(OaSysFlowNode::getFlcmbid, templeId)
                            .eq(OaSysFlowNode::getFjdmc, OaFlowConstant.JBZB_HJMC_DWLDSP));

                    if (oaJbzbgl.getFbm().contains(OaCommonFlowConstant.ORG_NAME_ZXFZR)) {
                        nextnodeId = flowNodeListdwld.get(0).getId();

                    } else if (oaFlowNodeDbrService.brksfzr()) {
                        nextnodeId = flowNodeList.get(0).getId();
                    } else {
                        nextnodeId = "";
                    }


                    Result result1 = newOajbzbFlowService.passJob(oaid, job.getId(), "同意", nextnodeId, "");
                    if (!result1.isSuccess()) {
                        return HttpResult.error(result.getMessage());
                    }
                    msg = "提交成功";
                    //提交完成后 更新待办信息
                    sysTzMessageService.tjMessage(oaid);
                    List<OaProcessBusiness> oaProcessBusinessList1 = oaProcessBusinessService.list(new LambdaQueryWrapper<OaProcessBusiness>()
                            .eq(OaProcessBusiness::getFpid, oaid));
                    OaProcessBusiness oaProcessBusiness = oaProcessBusinessList1.get(0);
                    OaProcessBusiness byId1 = oaProcessBusinessService.getById(oaProcessBusiness.getId());
                    byId1.setFsfkch(0);
                    byId1.setFcshdb(OaFlowConstant.FLOW_BLZT_YB);
                    oaProcessBusinessService.updateById(byId1);
                    myLcFlowService.recall(oaid);

                }

            }
        }

        HashMap map = new HashMap();
        map.put("msg",msg);
        map.put("oaMap",oaJbzbgl);
        map.put("jobMap",job);
        return HttpResult.ok(map);
    }

    /**
     * 加班值班保存
     */
    @AutoLog(value = "加班值班保存接口")
    @ApiOperation(value = "加班值班保存接口")
    @PostMapping(value = "/saveFlow")
    public HttpResult<?> saveFlow(@RequestBody OaFlowVo oaFlowVo) {
        String submitType = OaCommonFlowConstant.SUBMIT_TYPE_SAVE; // 保存

        String jobId = oaFlowVo.getJobid(); // 当前流程任务id
        String oaid = oaFlowVo.getOaid(); // 当前办公主键id
        String opinion = oaFlowVo.getOpinion(); // 办理意见
        if (StringUtils.isBlank(oaFlowVo.getLcmbCode())){
            oaFlowVo.setLcmbCode(OaFlowConstant.OA_JBZB);
        }

        if (StringUtils.isBlank(jobId)) {
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }
        // 流程处理
        Result httpResult = newOajbzbFlowService.handleFlow(oaFlowVo, null, jobId, oaid, submitType, opinion);
        if (!httpResult.isSuccess()) {
            return HttpResult.error(httpResult.getMessage());
        }
        Map map = new HashMap();
        HttpResult<Object> res = new HttpResult<>(true);
        res.setMessage("保存成功");
        res.setResult(map);
        return res;
    }

    /**
     * 加班值班提交接口
     */
    @AutoLog(value = "加班值班提交接口")
    @ApiOperation(value = "加班值班提交接口")
    @PostMapping(value = "/submitFlow")
    public HttpResult<?> submitFlow(@RequestBody OaFlowVo oaFlowVo) {

        String submitType = OaCommonFlowConstant.SUBMIT_TYPE_SUBMIT; // 提交

        if (StringUtils.isBlank(oaFlowVo.getLcmbCode())){
            oaFlowVo.setLcmbCode(OaFlowConstant.OA_JBZB);
        }
        String jobId = oaFlowVo.getJobid();
        String oaid = oaFlowVo.getOaid();
        String opinion = oaFlowVo.getOpinion();
        OaJbzbgl oaId = oaJbzbglService.getById(oaid);
        OaJobEntity jobid = spcySqsxJobService.getById(jobId);

        if (jobid.getFhjmc().equals(OaFlowConstant.JBZB_HJMC_JBBL)) {

        } else {
            oaId.setFlczt(OaCommonFlowConstant.FLOW_LCZB);
        }
        if (StringUtils.isBlank(oaId.getFsffqlc())) {
            oaId.setFsffqlc(OaCommonFlowConstant.SFFQLC_YES);
        }

        oaJbzbglService.updateById(oaId);


        if (StringUtils.isBlank(jobId)) {
            return HttpResult.error("流程任务id参数丢失，请联系管理员");
        }
        /* if (StringUtils.isBlank(opinion)){
            return HttpResult.error("请填写办理意见");
        }*/
        OaJobEntity nowJob = null;
        Result httpResult1 = newOajbzbFlowService.handleFlow(oaFlowVo, nowJob, jobId, oaid, submitType, opinion);
        if (!httpResult1.isSuccess()) {
            return HttpResult.error(httpResult1.getMessage());
        }
        List<OaProcessBusiness> oaProcessBusinessList1 = oaProcessBusinessService.list(new LambdaQueryWrapper<OaProcessBusiness>()
                .eq(OaProcessBusiness::getFpid, oaid));
        OaProcessBusiness oaProcessBusiness = oaProcessBusinessList1.get(0);
        OaProcessBusiness byId1 = oaProcessBusinessService.getById(oaProcessBusiness.getId());
        byId1.setFsfkch(0);
        byId1.setFcshdb(OaFlowConstant.FLOW_BLZT_YB);
        oaProcessBusinessService.updateById(byId1);
        //提交完成后 更新待办信息
        sysTzMessageService.tjMessage(oaid);
        myLcFlowService.recall(oaid);
        return HttpResult.ok("提交成功");
    }

    /**
     * 查询当前流程任务详情-通过当前流程任务id
     */
    @AutoLog(value = "查询当前流程任务详情-通过当前流程任务id")
    @ApiOperation(value = "查询当前流程任务详情-通过当前流程任务id")
    @ApiImplicitParam(value = "jobid", name = "流程任务id", required = true)
    @GetMapping(value = "queryJobByJobId")
    public HttpResult<?> queryJobByJobId(@RequestParam("jobid") String jobid) {
        if (StringUtils.isBlank(jobid)) {
            return HttpResult.error("流程任务id不能为空");
        }
        Map map = newOajbzbFlowService.getJobConcernByJobId(jobid);
        return HttpResult.ok(map);
    }


    /**
     * 获取已办列表-通过当前流程id-自定义退回
     *
     * @param jobid
     * @return
     */
    @AutoLog(value = "获取已办列表-通过当前流程id-自定义退回")
    @ApiOperation(value = "获取已办列表-通过当前流程id-自定义退回")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobid", value = "流程任务id"),
            @ApiImplicitParam(name = "isZdhj", value = "是否指定环节，默认：true，指定")
    })
    @GetMapping(value = "queryAllYbJob")
    public HttpResult<?> queryAllYbJob(@RequestParam(value = "jobid", defaultValue = "") String jobid,
                                       @RequestParam(value = "isZdhj", defaultValue = "true") boolean isZdhj) {
        List<Map<String, String>> currentJobPrevious = newOajbzbFlowService.getCurrentJobPrevious(jobid, isZdhj);
        return HttpResult.ok(currentJobPrevious);
    }

    /**
     * 退回环节
     *
     * @return
     */
    @AutoLog(value = "自定义-退回环节")
    @ApiOperation(value = "自定义-退回环节")
    @PostMapping(value = "returnUpperzdyFlowJob")
    public HttpResult<?> returnUpperzdyFlowJob(@RequestBody OaReturnVo oaReturnVo) {
        newOajbzbFlowService.returnZdJob(oaReturnVo);
        return HttpResult.ok("退回成功");
    }






    @AutoLog(value = "删除加班值班申请请示流程")
    @ApiOperation(value = "删除加班值班申请请示流程")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "jobids", value = "流程任务id,逗号分割", required = true)
    })
    @DeleteMapping(value = "deleteJbzbFlowJob")
    public HttpResult<?> deleteJbzbFlowJob(@RequestParam(value = "jobids") String jobids) {
        if (StringUtils.isBlank(jobids)) {
            return HttpResult.error("参数不能为空");
        }
        List<String> jobIdList = Arrays.asList(jobids.split(","));
        String logNr = "";
        Map<String, Object> map = new HashMap<>();
        if (CollectionUtils.isNotEmpty(jobIdList)) {
            List<OaJobEntity> jobList = spcySqsxJobService.listByIds(jobIdList);
            if (CollectionUtils.isNotEmpty(jobList)) {
                for (OaJobEntity job : jobList) {
                    spcySqsxJobService.removeById(job.getId());
                    OaJbzbgl oaLgqs = oaJbzbglService.getById(job.getFpid());
                    if (oaLgqs != null) {
                        oaJbzbglService.removeById(job.getFpid());

                        logNr = "删除加班值班申请" + job.getFhjmc() + ": ";
                        map = ObjectToMapUtils.objectToMap(oaLgqs);
                        logNr += LogUtils.MapToStringMethod(map);

                        spcyLogService.addLogs(job.getFhjmc(), logNr, job.getFpid(), OaLogConstant.LOGS_OA_JBZB, OaCommonFlowConstant.LOGS_SYS_TYPE_SC);
                    }
                }
            }
        }

        return HttpResult.ok("删除成功");
    }




}
